package cn.qingfeng.a004_chat_v3.server.handler;

import cn.qingfeng.a004_chat_v3.message.GquitRequestMessage;
import cn.qingfeng.a004_chat_v3.message.GquitResponseMessage;
import cn.qingfeng.a004_chat_v3.server.groupsession.Group;
import cn.qingfeng.a004_chat_v3.server.groupsession.GroupSession;
import cn.qingfeng.a004_chat_v3.server.groupsession.GroupSessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class GquitHandler extends SimpleChannelInboundHandler<GquitRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GquitRequestMessage msg) throws Exception {
        final GroupSession groupSession = GroupSessionFactory.getSession();

        if (msg == null) {
            return;
        }

        String username = msg.getFromUsername();
        String groupName = msg.getGroupName();
        Group group = groupSession.removeMember(groupName, username);
        if (group != null) {
            ctx.writeAndFlush(new GquitResponseMessage(true, groupName + "群退出成功"));
        } else {
            ctx.writeAndFlush(new GquitResponseMessage(false, groupName + "群不存在"));
        }
    }
}